require 'dbaccess.rb'
require 'rubygems'
require 'yahoofinance'
require 'ruby-debug'
require 'time'


class HistoricalQuote < DbAccess
  
  def initialize(hostname, username, password, dbname)
    super(hostname, username, password, dbname)
    @mycon = connect()
    @mycon.select_db(@dbname)
  end
  
  def close
    @mycon.close
  end
  
  
  def loadhistoricaldata(startdate, exchange)
      
      d1 = Date.parse(startdate)
      d2 = Date.today
      
      res = @mycon.query("select * from symbols where exchange = \"#{exchange}\"")
      res.each do |result|
      
        symbol = result[0].to_s
        puts "Processing Symbol #{symbol}..."
      
        str = "http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=#{d1.month}&b=#{d1.day}&c=#{d1.year}&d=#{d2.month}&e=#{d2.day}&f=#{d2.year}&g=d&ignore=.csv"
        puts str
        uri = URI(str)
        begin
          data = Net::HTTP.get_response(uri)
        rescue
          puts "Unknown error encountered for symbol #{symbol} !"
          next
        end
        if (!data.is_a?(Net::HTTPSuccess)) then
          puts "HTTP error for symbol #{symbol} !"
          next
        end
      
        data.body.each_line do |line|
          line = line.strip
          subs = line.split(",")
          if (subs[0].match("Date")) then
            next
          end
    
          sql = "REPLACE INTO `historicalquote` (`symbol`, `tradeDate`, `open`, `high`, `low`, `close`,
              `volume`, `adjClose`) 
              VALUES('#{symbol}', '#{Date.parse(subs[0].to_s).to_s}', #{subs[1].to_f}, 
              #{subs[2].to_f}, #{subs[3].to_f}, #{subs[4].to_f}, #{subs[5].to_f}, #{subs[6].to_f});"
              
          @mycon.query(sql)
              
        end
        
      end
      
      @mycon.close()
        
    end
    
      
end